/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonUtil {

  public static String toJsonString(Object o) {
    return JSON.toJSONString(o, SerializerFeature.WriteMapNullValue);
  }

  public static String toJsonString(Object o, boolean writeNullValue) {
    if (writeNullValue) {
      return JSON.toJSONString(o, SerializerFeature.WriteMapNullValue);
    } else {
      return JSON.toJSONString(o);
    }
  }

  public static void writeJsonToFile(Object o, File f) {
    try {
      FileUtils.writeStringToFile(f, toJsonString(o));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }


  public static <T> T parse(String s) {
    return (T) JSON.parse(s);
  }

  public static <T> T parse(InputStream inputStream) {
    String s;
    try {
      s = IOUtils.toString(inputStream);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return parse(s);
  }

  public static <T> T parse(String s, Class clazz) {
    JSON json = (JSON) JSON.parse(s);
    return (T) JSON.toJavaObject(json, clazz);
  }

  public static <T> T parse(File file) {
    return (T) parse(null, file);
  }

  public static <T> T parse(String charset, File file) {
    try {
      return parse(FileUtils.readFileToString(file, charset));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static <T> T parse(File file, Class clazz) {
    return (T) parse(null, file, clazz);
  }


  public static <T> T parse(String charset, File file, Class clazz) {
    JSON json = parse(charset, file);
    return (T) jsonToJava(json, clazz);
  }

  public static <T> T parseClasspathResource(String path) {
    InputStream inputStream = JsonUtil.class.getResourceAsStream(path);
    if (inputStream == null) {
      throw new RuntimeException("classpath resource:" + path + " doesn't exist");
    }
    return parse(inputStream);
  }


  public static <T> T jsonToJava(JSON json, Class clazz) {
    return (T) JSON.toJavaObject(json, clazz);
  }

  public static void main(String[] args) {}
}
